package org.fall.view.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.fall.view.constant.ViewConstant;
import org.fall.view.mapper.DailyNewspaperMapper;
import org.fall.view.mapper.MailBoxMapper;
import org.fall.view.mapper.MemberLeaderMapper;
import org.fall.view.mapper.MemberUserMapper;
import org.fall.view.model.ResultEntity;
import org.fall.view.model.dto.MailBoxDTO;
import org.fall.view.model.dto.MemberUserDTO;
import org.fall.view.model.dto.NewspaperSubmitDTO;
import org.fall.view.model.po.DailyNewspaperPO;
import org.fall.view.model.po.LeaderInfoPO;
import org.fall.view.model.po.MailBoxPO;
import org.fall.view.model.po.MemberUserPO;
import org.fall.view.model.vo.DailyNewspaperVO;
import org.fall.view.model.vo.MailBoxVO;
import org.fall.view.model.vo.MemberUserVO;
import org.fall.view.service.MemberUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sprogFall
 * @since 2021/4/12 15:22
 */
@Service
public class MemberUserServiceImpl implements MemberUserService {

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private MemberLeaderMapper memberLeaderMapper;

    @Resource
    private DailyNewspaperMapper dailyNewspaperMapper;

    @Resource
    private MailBoxMapper mailBoxMapper;

    @Override
    public ResultEntity login(MemberUserDTO dto, HttpSession session) {
        QueryWrapper<MemberUserPO> queryWrapper = new QueryWrapper<>();
        // 用户必须未被删除
        queryWrapper.eq("delete_token", 0);
        queryWrapper.eq("username", dto.getUsername());
        queryWrapper.eq("password", dto.getPassword());
        MemberUserPO po = memberUserMapper.selectOne(queryWrapper);
        if (po == null) {
            return ResultEntity.failed(ViewConstant.LOGIN_FILED);
        }
        session.setAttribute("loginUser", po.getName());
        session.setAttribute("loginId", po.getId());
        return ResultEntity.successWithData(po.getName());
    }

    @Override
    public List<LeaderInfoPO> getLeaderList(Integer except) {
        QueryWrapper<LeaderInfoPO> queryWrapper = new QueryWrapper<>();
        // 抄送人需要排除登录用户自己
        queryWrapper.ne("leader_id", except);
        return memberLeaderMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity submitPaper(NewspaperSubmitDTO dto, Integer writerId) {
        DailyNewspaperPO po = new DailyNewspaperPO();
        BeanUtils.copyProperties(dto, po);
        po.setWriterId(writerId);
        // 插入日报数据库信息
        int insert = dailyNewspaperMapper.insert(po);
        // 插入抄送人信息
        for (Integer leaderId : dto.getLeaderId()) {
            dailyNewspaperMapper.insertCopyForInfo(po.getId(), leaderId);
        }
        return ResultEntity.successWithoutData();
    }

    @Override
    public List<DailyNewspaperVO> getMyNewspaper(Integer loginId) {
        return dailyNewspaperMapper.getDailyNewsPaperInfoByWriterId(loginId);
    }

    @Override
    public List<DailyNewspaperVO> getLeaderNewspaper(Integer leaderId) {
        return dailyNewspaperMapper.getDailyNewspaperInfoByLeaderId(leaderId);
    }

    @Override
    public List<MemberUserVO> getMemberUserVOList() {
        QueryWrapper<MemberUserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_token", 0);
        queryWrapper.select("id", "department", "name", "email");
        queryWrapper.orderByAsc("department");
        List<MemberUserPO> list = memberUserMapper.selectList(queryWrapper);
        List<MemberUserVO> res = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (MemberUserPO po : list) {
                res.add(MemberUserVO.convertPoToVo(po));
            }
        }
        return res;
    }

    @Override
    public ResultEntity sendMail(MailBoxDTO dto, Integer sendUserId) {
        MailBoxPO po = new MailBoxPO();
        BeanUtils.copyProperties(dto, po);
        // 设置po的发送者与状态
        if (po.getAnonymous() == 0) {
            // 非匿名，设置发送者id
            po.setSendUserId(sendUserId);
        } else {
            // 匿名用户默认userId设置为-1
            po.setSendUserId(-1);
        }
        // 发送态
        po.setStatus(1);
        // 判断当前登录用户是否有草稿
        MailBoxPO currPo = existMail(sendUserId);
        int num;
        if (currPo != null) {
            // 草稿存在，使用update发送草稿
            po.setId(currPo.getId());
            num = mailBoxMapper.updateById(po);
        } else {
            // 草稿不存在，直接insert发送草稿
            num = mailBoxMapper.insert(po);
        }
        if (num == 1) {
            return ResultEntity.successWithoutData();
        }
        return ResultEntity.failed(ViewConstant.SEND_MAIL_FAILED);
    }

    @Override
    public ResultEntity saveMail(MailBoxDTO dto, Integer sendUserId) {
        MailBoxPO po = new MailBoxPO();
        BeanUtils.copyProperties(dto, po);
        // 设置po的发送者id与状态（草稿态）
        po.setSendUserId(sendUserId);
        po.setStatus(0);
        int num;
        // 判断当前登录用户是否有草稿存在于数据库中
        MailBoxPO currPo = existMail(sendUserId);
        if (currPo != null) {
            // 草稿存在，更新草稿
            po.setId(currPo.getId());
            num = mailBoxMapper.updateById(po);
        } else {
            // 草稿不存在，新增草稿
            num = mailBoxMapper.insert(po);
        }
        if (num == 1) {
            return ResultEntity.successWithoutData();
        }
        return ResultEntity.failed(ViewConstant.SAVE_MAIL_FAILED);
    }

    @Override
    public MailBoxVO getSavedMail(Integer loginId) {
        MailBoxPO po = existMail(loginId);
        MailBoxVO vo = new MailBoxVO();
        if (po != null) {
            BeanUtils.copyProperties(po, vo);
        }
        return vo;
    }

    @Override
    public List<MailBoxVO> getAcceptMail(Integer loginId, String type, String anonymous) {
        return mailBoxMapper.selectMailListByAcceptId(loginId, type, anonymous);
    }

    @Override
    public List<MailBoxVO> getSendMail(Integer loginId, String type) {
        return mailBoxMapper.selectMailListBySendId(loginId, type);
    }

    /**
     * 查找当前用户是否存在草稿
     * @return 查找结果
     */
    private MailBoxPO existMail(Integer sendUserId) {
        QueryWrapper<MailBoxPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("send_user_id", sendUserId).eq("status", 0);
        return mailBoxMapper.selectOne(queryWrapper);
    }
}
